import json

import re

from django.contrib.auth import login, authenticate, logout
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import JsonResponse
from django.shortcuts import render
import logging
logger = logging.getLogger('django')
# Create your views here.
from django.utils.decorators import method_decorator
from django.views import View
from django.views.decorators.csrf import ensure_csrf_cookie

from meiduo.utils.view import LoginRequireMixin
from .models import User, Address
from django_redis import get_redis_connection
# 判断用户名是否重复
class UsernameCountView(View):
    def get(self,request,username):
        username = username.split('/')
        username = username[0]
        try:

            count = User.objects.filter(username=username).count()

        except Exception as e:
            return JsonResponse({'code':400,
                                 'errmsg':'访问数据库失败'})
        return JsonResponse({'code': 0,
                             'errmsg': 'ok',
                            'count': count})

class MobileCountView(View):
    def get(self,request,mobile):
        mobile = mobile.split('/')
        mobile = mobile[0]
        try:
            count = User.objects.filter(mobile=mobile).count()
        except Exception as e:
            return JsonResponse({'code':400,
                                 'errmsg':"访问数据库失败"})
        return JsonResponse({'code':200,
                             'errmsg':'ok',
                             'count':count})
# 注册
class RegisterView(View):
    @method_decorator(ensure_csrf_cookie)
    def post(self,request):
        dict = json.loads(request.body.decode())
        username = dict.get('username')
        password = dict.get('password')
        password2 = dict.get('password2')
        mobile = dict.get('mobile')
        allow = dict.get('allow')
        sms_code = dict.get('sms_code')

        if not all([username,password,password2,mobile,allow,sms_code]):
            return JsonResponse({'code':400,
                                 'errmsg':"参数不全"})
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$',username):
            return JsonResponse({'code':400,
                                 'errmsg':'用户名格式有误'})
        if not re.match(r'^[a-zA-Z0-9]{8,20}',password):
            return JsonResponse({'code':400,
                                 'errmsg':'密码格式不对'})
        if password != password2:
            return JsonResponse({'code':400,
                                 'errmsg':'两次不一样'})
        if not re.match(r'^1[3-9]\d{9}$',mobile):
            return JsonResponse({'code':400,
                                 'errmsg':'mobile格式不对'})
        if allow != True:
            return JsonResponse({'code':400,
                                 'errmsg':'allow格式不对'})
        redis_conn = get_redis_connection('verify_code')
        sms_code_server = redis_conn.get('sms_%s' % mobile)
        if not sms_code_server:
            return JsonResponse({'code':400,
                                 'errmsg':"验证码过期"})
        if sms_code != sms_code_server.decode():
            return JsonResponse({'code':400,
                                 'errmsg':
                                 '验证码有误'})
        try:
            user = User.objects.create_user(username=username,password=password,mobile=mobile)
        except Exception as e:
            return JsonResponse({'code':400,
                                 'errmsg':'数据保存失败'})

        login(request,user)
        response = JsonResponse({'code': 0,
                                 'errmsg': 'ok'})
        response.set_cookie('username',
                            user.username,
                            max_age=3600 * 24 * 14)
        return response

# 登陆
class LoginView(View):
    def post(self,request):
        dict = json.loads(request.body.decode())
        username = dict.get('username')
        password = dict.get('password')
        remembered = dict.get('remembered')
        if not all([username,password]):
            return JsonResponse({'code':400,
                                 'errmsg':'参数不全'})
        user = authenticate(username=username,password=password)
        if user is None:
            return JsonResponse({'code':400,
                                 'errmsg':'用户名或密码错误'})
        login(request,user)
        if remembered != True:
            request.session.set_expiry(0)
        else:
            request.session.set_expiry(None)
        response = JsonResponse({'code':0,
                             'errmsg':'ok'})
        response.set_cookie('username',
                            user.username,
                            max_age=3600*24*14)
        return response


# 退出登陆
class LogoutView(View):
 def delete(self,request):
     # 清除session
    logout(request)
     # 清除cookie
    response = JsonResponse({'code':0,
                             'errmsg':'ok'})
    response.delete_cookie('username')
    return response

# 用户中心
class UserInfoView(LoginRequireMixin,View):
    def get(self,request):
        dict = {
            "username": request.user.username,
            "mobile": request.user.mobile,
            "email": request.user.email,
            "email_active": request.user.email_active
        }

        return JsonResponse({'code': 0,
                             'errmsg': 'ok',
                             'info_data': dict})


# 新增收货地址
class CreateAddressView(View):
    def post(self, request):
        '''新增地址接口'''

        try:
            # 1.从mysql中获取该用户的所有没有删除的地址个数
            count = Address.objects.filter(user=request.user,
                                           is_deleted=False).count()
        except Exception as e:
            return JsonResponse({'code':400,
                                 'errmsg':'获取该用户的地址信息出错'})

        # 2.判断该个数是否>=20,如果是,返回
        if count >= 20:
            return JsonResponse({'code': 400,
                                 'errmsg': '地址个数超过20个'})

        # 3.接收参数(json)
        dict = json.loads(request.body.decode())
        receiver = dict.get('receiver')
        province_id = dict.get('province_id')
        city_id = dict.get('city_id')
        district_id = dict.get('district_id')
        place = dict.get('place')
        mobile = dict.get('mobile')
        tel = dict.get('tel')
        email = dict.get('email')

        # 4.总体检验
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return JsonResponse({'code': 400,
                                 'errmsg': '缺少必传参数'})

        # 5.单个检验mobile
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code': 400,
                                 'errmsg': 'mobile格式不正确'})

        # 6.tel
        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return JsonResponse({'code': 400,
                                     'errmsg': 'tel格式不正确'})
        # 7.email
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return JsonResponse({'code': 400,
                                     'errmsg': 'email格式不正确'})
        try:
            # 8.往Address表中增加地址信息
            address = Address.objects.create(
                user = request.user,
                province_id = province_id,
                city_id = city_id,
                district_id = district_id,
                title = receiver,
                receiver = receiver,
                place = place,
                mobile = mobile,
                tel = tel,
                email = email
            )
            # 9.判断默认地址是否存在,如果不存在,把刚刚增加的地址作为默认地址
            if not request.user.default_address:
                request.user.default_address = address
                request.user.save()
        except Exception as e:
            return JsonResponse({'code': 400,
                                 'errmsg': '增加地址失败'})

        # 10.拼接参数, 返回
        dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }

        return JsonResponse({'code':0,
                             'errmsg':'ok',
                             'address':dict})

# 展示收货地址

class AddressView(View):
    def get(self,request):

        addresses = Address.objects.filter(user=request.user,is_deleted=False)
        address_dict = []
        for address in addresses:
            dict = {
                "id": address.id,
                "title": address.title,
                "receiver": address.receiver,
                "province": address.province.name,
                "city": address.city.name,
                "district": address.district.name,
                "place": address.place,
                "mobile": address.mobile,
                "tel": address.tel,
                "email": address.email
            }
            if request.user.default_address.id == address.id:
                address_dict.insert(0,dict)
            else:
                address_dict.append(dict)
        default_address_id = request.user.default_address_id

        # 6.拼接参数, 返回json
        return JsonResponse({'code': 0,
                             'errmsg': 'ok',
                             'default_address_id': default_address_id,
                             'addresses': address_dict})

# 修改地址
class UpdateDestroyAddressView(View):

    def put(self, request, address_id):

        '''修改地址的接口'''
        # 1.接收前端传如的数据
        dict = json.loads(request.body.decode())
        receiver = dict.get('receiver')
        province_id = dict.get('province_id')
        city_id = dict.get('city_id')
        district_id = dict.get('district_id')
        place = dict.get('place')
        mobile = dict.get('mobile')
        tel = dict.get('tel')
        email = dict.get('email')

        # 2.检验数据
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return JsonResponse({'code': 400,
                                 'errmsg': '缺少必传参数'})

            # 5.单个检验mobile
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code': 400,
                                 'errmsg': 'mobile格式不正确'})

            # 6.tel
        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return JsonResponse({'code': 400,
                                     'errmsg': 'tel格式不正确'})
            # 7.email
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return JsonResponse({'code': 400,
                                     'errmsg': 'email格式不正确'})

        # 3.获取address_id对应的查询集.调用查询集的update方法,更新
        try:
            Address.objects.filter(id=address_id).update(
                user=request.user,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                title=receiver,
                receiver=receiver,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email
            )

            address = Address.objects.get(id=address_id)

        except Exception as e:
            return JsonResponse({'code': 400,
                                 'errmsg': '更新失败'})

        # 4.拼接参数, 返回
        dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }

        return JsonResponse({'code':0,
                             'errmsg':'ok',
                             'address':dict})
    def delete(self, request, address_id):
        '''删除address_id对应的地址'''
        try:
            # 1.根据地址的id获取地址对象
            address = Address.objects.get(id=address_id)

            # 2.删除该地址对象(逻辑删除)
            # 错误的写法: address.deleted()
            address.is_deleted = True

            # 3.保存
            address.save()
        except Exception as e:
            return JsonResponse({'code':400,
                                 'errmsg':'删除失败'})

        # 4.返回结果
        return JsonResponse({'code':0,
                             'errmsg':'ok'})

# 设置默认地址
class DefaultAddressView(View):
    def put(self,request,address_id):
        try:
            address = Address.objects.get(id=address_id)
            request.user.default_address = address
            request.user.save()
        except Exception as e:
            logger.error(e)
            return JsonResponse({'code':400,
                                 'errmsg':'设置失败'})
        return JsonResponse({'code':0,
                             'errmsg':'设置默认地址成功',
                             })

# 修改地址标题
class ChangeAddressTitleView(View):
    def put(self,request,address_id):

        json_dict = json.loads(request.body.decode())
        title = json_dict.get('title')
        try:
            address = Address.objects.get(id=address_id)
            address.title = title
            address.save()
        except Exception as e:
            return JsonResponse({'code':400,
                                 'errmsg':'设置失败'})
        return JsonResponse({'code':0,
                             'errmsg':'设置成功'})


# 修改密码
class ChangePasswordView(LoginRequiredMixin, View):

    def put(self, request):
        '''修改密码接口'''
        dict = json.loads(request.body.decode())
        old_password = dict.get('old_password')
        new_password = dict.get('new_password')
        new_password2 = dict.get('new_password2')
        if not all([old_password,new_password,new_password2]):
            return JsonResponse({'code':400,
                                 'errmsg':'缺少参数'})
        if not request.user.check_password(old_password):
            return JsonResponse({'code':400,
                                 'errmsg':'原始密码不对'})
        if not re.match(r'^[0-9a-zA-Z_-]{8,20}$',new_password):
            return JsonResponse({'code':400,
                                 'errmsg':'密码至少8位'})
        if new_password != new_password2:
            return JsonResponse({'code':400,
                                  'errmsg':'两次密码不一致'})
        try:
            request.user.set_password(new_password)
            request.user.save()
        except Exception as e:
            logger.error(e)
            return JsonResponse({'code':400,
                                 'errmsg':'修改密码失败'})
        logout(request)
        response = JsonResponse({'code':0,
                                 'errmsg':'ok'})
        response.delete_cookie('username')
        return response

